package com.pingpang.netty.client;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Proxy;

public class RpcFactoryBean<T> implements FactoryBean<T> {

    private Class<T> rpcInterface;

    @Autowired
    RpcFactory<T> factory;

    public RpcFactoryBean(Class<T> rpcInterface) {
    	this.rpcInterface=rpcInterface;
        factory=new RpcFactory<>();
    }

    public RpcFactoryBean(Class<T> rpcInterface, RpcFactory<T> factory) {
        this.rpcInterface = rpcInterface;
        this.factory=factory;
    }

    public T getObject() throws Exception {
        return getRpc();
    }

    public Class<?> getObjectType() {
        return this.rpcInterface;
    }

    public boolean isSingleton() {
        return true;
    }

    public <T> T getRpc() {
        return (T) Proxy.newProxyInstance(rpcInterface.getClassLoader(), new Class[] { rpcInterface },factory);
    }

	public RpcFactory<T> getFactory() {
		return factory;
	}

	public void setFactory(RpcFactory<T> factory) {
		this.factory = factory;
	}
    
}
